<?php

namespace app\model;

//use support\Model;
use app\controller\wmapi\IndexController;
use app\controller\wmapi\PublicCommentController;
use support\Db;
use Illuminate\Database\Eloquent\Model;
use function GuzzleHttp\json_decode;

class WaOrdersPurchase
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_orders_purchase';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public static function all($condition, $whereNotIn)
    {
        $condition [] = ['is_show', '=', 1];
        $list = Db::table('wa_orders_purchase')
            ->select('*')
            ->where($condition)
            ->whereNotIn('purchase_orders_status', $whereNotIn)
            ->orderBy('id', 'desc')
            ->get();
        if ($list) {

            foreach ($list as $k) {
                if ($k->purchase_orders_type) {
                    // 1 销售订单直接创建的采购单 2  间接（单独采购）创建的采购单
                }
                if ($k->car_type) {
                    // 1轿车 2 SUV 3 MPV 4 跑车 5新能源
                }
                if ($k->purchase_orders_status) {
                    // 0 草稿 1审批中 2待签署采购合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
                }
                if ($k->supplier_type) {
                    // 供应商类型
                }

                if ($k->confirm_signing_model_one) {
                    $k->confirm_signing_model_one = json_decode($k->confirm_signing_model_one);
                }
                if ($k->confirm_signing_model_two) {
                    $k->confirm_signing_model_two = json_decode($k->confirm_signing_model_two);
                }

                //下单人
                if (!$k->sales_order_admin_id) {
                    $k->sales_order_admin_id = $k->sales_order_admin_id;
                    $k->sales_order_created_at = $k->created_at;
                    $k->sales_order_admin_name = $k->admin_name;
                }

                // 供应商数据
                if ($k->supplier_id) {
                    $supplier_data = WaSupplier::find(['id' => $k->supplier_id]);
                    $supplier_data = json_decode($supplier_data);
                    $k->supplier_data = $supplier_data;
                } else {
                    $k->supplier_data = '';
                }

                $k->purchase_orders_status_name = IndexController::purchaseOrderStatusName($k->purchase_orders_status);

                $sums = WaOrdersPurchaseRelevance::sums(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $counts = WaOrdersPurchaseRelevance::counts(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $requested_price = WaPurchasePayrollRequisition::sums(['purchase_order_sn' => $k->purchase_order_sn]);
                $children = WaOrdersPurchaseRelevance::all(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $children = json_decode($children);
                if ($children) {
                    foreach ($children as $key) {
//                        $key->other_price = json_decode($key->other_price);
                    }
                }
                $k->children = $children;
                $k->purchase_total_price = round($sums, 2);
                $k->total_count = intval($counts);
                $k->requested_price = round($requested_price, 2);

            }
        }
        return json_encode($list);

    }

    public static function allChildren($condition)
    {

        $list = Db::table('wa_orders_purchase')
            ->select('purchase_order_sn')
            ->where($condition)
            ->get();

        if ($list) {

            foreach ($list as $k) {
                $children = WaOrdersPurchaseRelevance::all(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $children = json_decode($children);
                if ($children) {
                    foreach ($children as $key) {
//                        $key->other_price = json_decode($key->other_price);
                    }
                }
                $k->children = $children;
            }
        }
        return json_encode($list);

    }


    public static function created($data)
    {
        $result = Db::table('wa_orders_purchase')->insertGetId($data);
        return $result;
    }

    public static function updated($data, $where)
    {
        $result = Db::table('wa_orders_purchase')->where($where)->update($data);
        return $result;
    }

    public static function list($adminId, $page, $pageNum, $whereIn, $whereNotIn, $fields = ['*'],$whereStatusIn = [], $condition = [], $between = [], $conditions = [])
    {
        $condition [] = ['is_show', '=', 1];
        $offset = ($page - 1) * $pageNum;
//        if ($between) {
//            $model = Db::table('wa_orders_purchase')
//                ->select($fields)
//                ->where($condition)
//                ->where($conditions)
//                ->whereNotIn('purchase_orders_status', $whereNotIn)
//                ->whereBetween('created_at', $between);
//        }
//        else {
//            $model = Db::table('wa_orders_purchase')
//                ->select($fields)
//                ->where($condition)
//                ->where($conditions)
//                ->whereNotIn('purchase_orders_status', $whereNotIn);
////                ->whereIn('admin_id',$whereIn);
//        }

        $model = Db::table('wa_orders_purchase')
            ->select($fields)
            ->where($condition)
            ->where($conditions);
        if ($between) {
            $model->whereBetween('created_at', $between);
        }
        if ($whereIn) {
            $model->whereIn('admin_id',$whereIn);
        }

        if ($whereStatusIn) {
            $model->whereIn('purchase_orders_status',$whereStatusIn);
        }
        if ($whereNotIn) {
            $model->whereNotIn('purchase_orders_status',$whereNotIn);
        }

        $count = $model->count();
        $list = $model
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($pageNum)
            ->get();
//        ->paginate($pageNum);

        if ($list) {
            foreach ($list as $k) {

                if ($k->registration_company_info) {
                    $k->registration_company_info = json_decode($k->registration_company_info);
                }
                if ($k->transfer_export_company_info) {
                    $k->transfer_export_company_info = json_decode($k->transfer_export_company_info);
                }
                if ($k->purchase_orders_type) {
                    // 1 销售订单直接创建的采购单 2  间接（单独采购）创建的采购单
                }
                if ($k->car_type) {
                    // 1轿车 2 SUV 3 MPV 4 跑车 5新能源
                }
                if ($k->purchase_orders_status) {
                    // 0 草稿 1审批中 2待签署采购合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
                }
                if ($k->supplier_type) {
                    // 供应商类型
                }

                //下单人
                if (!$k->sales_order_admin_id) {
                    $k->sales_order_admin_id = $k->admin_id;
                    $k->sales_order_created_at = $k->created_at;
                    $k->sales_order_admin_name = $k->admin_name;
                }

                $k->purchase_orders_status_name = IndexController::purchaseOrderStatusName($k->purchase_orders_status);

//                $where = [];
//                $where [] = ['purchase_order_sn_parent','=',$k->purchase_order_sn];
//                $count = WaOrdersPurchaseRelevance::counts($where);
//                $k->count = $count;


                $sums = WaOrdersPurchaseRelevance::sums(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $counts = WaOrdersPurchaseRelevance::counts(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $k->count = $counts;
                $children = WaOrdersPurchaseRelevance::all(['purchase_order_sn_parent' => $k->purchase_order_sn]);
                $children = json_decode($children);
                if ($children) {
                    foreach ($children as $key) {

//                        $key->other_price = json_decode($key->other_price);

                    }
                }
                $k->children = $children;
                $k->purchase_total_price = round($sums, 2);
                $k->total_count = intval($counts);


                // 采购定金
                $k->deposit_price = round($k->deposit_price, 2);
                $deposit_sums = 0; //已付款定金
                $deposit_suming = 0; //请款中定金
                if (!$k->deposit_price) {
                    // 定金为 0 无需请款
                    $k->deposit_price = 0;
                    $k->deposit_payroll_status = 0;
                } else {
                    // 定金大于 0  需要请款
                    $k->deposit_payroll_status = 3; // 定金未足额请款

                    //已请款定金金额
                    $purchase_payroll_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 1], ['status', '<', 4]]);
                    $purchase_payroll_find = json_decode($purchase_payroll_find);
                    if ($purchase_payroll_find) {
                        //有请款
                        // 请款定金金额
                        $k->deposit_price = round($k->deposit_price, 2);
                        // 已付款定金
                        $deposit_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 1]]);

                        // 定金请款中
                        $deposit_suming = WaPurchasePayrollRequisition::suming([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 1]]);
                        if ($deposit_suming) {
                            $k->deposit_payroll_status = 1;

                        } elseif ($deposit_sums > 0 && $deposit_sums < $k->deposit_price) {
                            //未足额请款
                            $k->deposit_payroll_status = 3;
                        } elseif ($deposit_sums >= $k->deposit_price) {
                            //已足额请款
                            $k->deposit_payroll_status = 2;
                        }else{
                            //未请款
                            $k->deposit_payroll_status = 4;
                        }


                    }else{
                        //未请款
                        $k->deposit_payroll_status = 4;
                    }
                }
                PublicCommentController::请款单状态;
                if ($k->deposit_payroll_status == 0) {
                    $k->deposit_payroll_status_name = '无定金';
                } elseif ($k->deposit_payroll_status == 1) {
                    $k->deposit_payroll_status_name = '请款审批中';
                } elseif ($k->deposit_payroll_status == 2) {
                    $k->deposit_payroll_status_name = '已足额请款';
                } elseif ($k->deposit_payroll_status == 3) {
                    $k->deposit_payroll_status_name = '未足额请款';

                } elseif ($k->deposit_payroll_status == 4) {
                    $k->deposit_payroll_status_name = '未请款';

                } else {
                    $k->deposit_payroll_status_name = '未请款';
                }

                $data_error = [
                    '错误：定金请款状态异常',
                    '采购订单编号：' . $k->purchase_order_sn,
                    '采购订单定金状态：' . $k->deposit_payroll_status,
                    '请款定金金额：' . $k->deposit_price,
                    '已付款定金：' . $deposit_sums,
                    '定金请款中：' . $deposit_suming,
                    '采购订单编号：' . $k->purchase_order_sn,
                ];
                IndexController::logErrorNew('Purchase-static-list', $data_error);

                // 尾款肯定大于 0（这个无需在这里判断）  需要请款
                $k->balance_payroll_status = 3; // 尾款未足额请款
                //已请款尾款金额
                $purchase_payroll_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 2], ['status', '<', 4]]);
                $purchase_payroll_find = json_decode($purchase_payroll_find);
                if ($purchase_payroll_find) {
                    //有请款
                    // 请款定金额
                    $k->deposit_price = round($k->deposit_price, 2);
                    // 采购尾款
                    $balance_price = round($k->total_amount, 2) - $k->deposit_price;
                    // 已支付尾款
                    $balance_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 2]]);

                    // 尾款请款中
                    $balance_suming = WaPurchasePayrollRequisition::suming([['purchase_order_sn', '=', $k->purchase_order_sn], ['payroll_requisition_type', '=', 2]]);
                    if ($balance_suming) {
                        //请款中
                        $k->balance_payroll_status = 1;
                    } elseif ($balance_sums > 0 && $balance_sums < $balance_price) {
                        //未足额请款
                        $k->balance_payroll_status = 3;
                    } elseif ($balance_sums >= $balance_price) {
                        //已足额请款
                        $k->balance_payroll_status = 2;
                    }else{
                        //未请款
                        $k->balance_payroll_status = 4;
                    }
                }else{
                    //未请款
                    $k->balance_payroll_status = 4;
                }
                PublicCommentController::请款单状态;
                if ($k->balance_payroll_status == 1) {
                    $k->balance_payroll_status_name = '请款审批中';
                } elseif ($k->balance_payroll_status == 2) {
                    $k->balance_payroll_status_name = '已足额请款';
                } elseif ($k->balance_payroll_status == 3) {
                    $k->balance_payroll_status_name = '未足额请款';

                } elseif ($k->balance_payroll_status == 4) {
                    $k->balance_payroll_status_name = '未请款';

                }  else {
                    $k->balance_payroll_status_name = '暂无';
                }


            }
        }
        return json_encode(['list' => $list, 'count' => $count]);


    }

    public static function find($condition)
    {
        $res = Db::table('wa_orders_purchase')
            ->where($condition)
            ->first();
        if ($res) {
            $k = $res;
            if ($k->confirm_signing_model_one) {
                $k->confirm_signing_model_one = json_decode($k->confirm_signing_model_one);
            }
            if ($k->confirm_signing_model_two) {
                $k->confirm_signing_model_two = json_decode($k->confirm_signing_model_two);
            }

            if ($k->registration_company_info) {
                $k->registration_company_info = json_decode($k->registration_company_info);
            }
            if ($k->transfer_export_company_info) {
                $k->transfer_export_company_info = json_decode($k->transfer_export_company_info);
            }
            $k->purchase_orders_status_name = IndexController::purchaseOrderStatusName($k->purchase_orders_status);


            $res = $k;
        }
        return json_encode($res);
    }

    public static function findByField($fields, $condition)
    {
        $res = Db::table('wa_orders_purchase')
            ->select($fields)
            ->where($condition)
            ->first();
        if ($res) {
            $k = $res;
            if ($k->registration_company_info) {
                $k->registration_company_info = json_decode($k->registration_company_info);
            }
            if ($k->transfer_export_company_info) {
                $k->transfer_export_company_info = json_decode($k->transfer_export_company_info);
            }
            // 采购订单状态 "新版：0 草稿 1 审批中 2 待签署采购合同 3 待支付定金 5 待配车 6 已完成 7 已作废 9 审批失败";
//            if ($k->purchase_orders_status == 0) {
//                $k->purchase_orders_status_name = '草稿';
//            } elseif ($k->purchase_orders_status == 1) {
//                $k->purchase_orders_status_name = '审批中';
//            } elseif ($k->purchase_orders_status == 2) {
//                $k->purchase_orders_status_name = '待签署采购合同';
//            } elseif ($k->purchase_orders_status == 3) {
//                $k->purchase_orders_status_name = '待支付定金';
//            } elseif ($k->purchase_orders_status == 5) {
//                $k->purchase_orders_status_name = '待配车';
//            } elseif ($k->purchase_orders_status == 6) {
//                $k->purchase_orders_status_name = '已完成';
//            } elseif ($k->purchase_orders_status == 7) {
//                $k->purchase_orders_status_name = '已作废';
//            } elseif ($k->purchase_orders_status == 9) {
//                $k->purchase_orders_status_name = '审批驳回';
//            } elseif ($k->purchase_orders_status == 10) {
//                $k->purchase_orders_status_name = '审批通过';
//            } elseif ($k->purchase_orders_status == 11) {
//                $k->purchase_orders_status_name = '待支付尾款';
//            }else{
//                $k->purchase_orders_status_name = '暂无此状态';
//            }
            $k->purchase_orders_status_name = IndexController::purchaseOrderStatusName($k->purchase_orders_status);


            $res = $k;
        }
        return json_encode($res);
    }


    public static function findApprove($adminId, $condition, $order_pur_data)
    {
        $res = Db::table('wa_orders_purchase')
            ->where($condition)
            ->first();
        if ($res) {
            if ($res->confirm_signing_model_one) {
                $res->confirm_signing_model_one = json_decode($res->confirm_signing_model_one);
            }
            if ($res->confirm_signing_model_two) {
                $res->confirm_signing_model_two = json_decode($res->confirm_signing_model_two);
            }


            if ($res->registration_company_info) {
                $res->registration_company_info = json_decode($res->registration_company_info);
            }
            if ($res->transfer_export_company_info) {
                $res->transfer_export_company_info = json_decode($res->transfer_export_company_info);
            }
            $where_bill_details = [];
            $where_bill_details [] = ['purchase_order_sn', '=', $res->purchase_order_sn];
            $bill_details = WaOrdersPurchaseAmountDetail::all($where_bill_details);

            if ($bill_details) {
                $bill_details = json_decode($bill_details);

                foreach ($bill_details as $ke) {
                    if ($ke->purchase_order_sn) {
                        $where_payroll = [];
                        $where_payroll [] = ['purchase_order_sn', '=', $ke->purchase_order_sn];
                        $where_payroll [] = ['price_name', '=', $ke->price_name];
                        $where_payroll [] = ['module_type', '=', 1]; // 1 采购模块 2 车辆管理模块
                        $payroll_requisition = WaPurchasePayrollRequisition::allByPur($where_payroll);
                        $payroll_requisition = json_decode($payroll_requisition);


                        $ke->requested_price = WaPurchasePayrollRequisition::sums($where_payroll);
                        if ($payroll_requisition) {
                            // 总金额
                            $ke->total_amount = round($ke->total_amount, 2);
                            // 已请款
                            $ke->requested_price = round(WaPurchasePayrollRequisition::sums($where_payroll), 2);
                            // 请款中
                            $ke->requested_pricing = round(WaPurchasePayrollRequisition::suming($where_payroll), 2);;
                            //  待请款
                            $ke->wait_price = $ke->total_amount - $ke->requested_price - $ke->requested_pricing;

                            $ke->payroll_requisition = $payroll_requisition;
                        } else {
                            $ke->payroll_requisition = [];
                        }
                    } else {
                        $ke->payroll_requisition = [];
                    }

                }
            }
            $res->bill_details = $bill_details; //  采购账单明细


            $approve_data = WaPurchaseOrdersExamineApprove::find($adminId, [['purchase_order_sn', '=', $res->purchase_order_sn], ['po_no', '=', $order_pur_data->po_no,], ['status', '!=', 3]]);
            $approve_data = json_decode($approve_data);
            if ($approve_data) {
                $approve = WaPurchaseOrdersExamineApproveFlow::all(
                    ['purchase_order_sn' => $res->purchase_order_sn, 'po_no' => $approve_data->po_no, 'status' => 2]);
                $approve = json_decode($approve);
                if ($approve) {
                    $approve_status = 2; // 已驳回
                    $approve_status_name = '已驳回';

                } else {
                    $approve = WaPurchaseOrdersExamineApproveFlow::all(
                        ['purchase_order_sn' => $res->purchase_order_sn, 'po_no' => $approve_data->po_no, 'status' => 1]);
                    $approve = json_decode($approve);
                    if ($approve) {
                        $approve_status = 1; // 已审批
                        $approve_status_name = '已审批';
                    } else {
                        $approve = WaPurchaseOrdersExamineApproveFlow::all(
                            ['purchase_order_sn' => $res->purchase_order_sn, 'po_no' => $approve_data->po_no, 'status' => 0]);
                        $approve = json_decode($approve);
                        if ($approve) {
                            $approve_status = 0; // 待审批
                            $approve_status_name = '待审批';
                        } else {
                            $approve_status = 999;// 待提交审批
                            $approve_status_name = '待提交审批';
                        }
                    }

                }
            } else {
                $approve_status = 10001;// 待提交审批
                $approve_status_name = '待提交审批/或不是审批人员';
            }


            $res->approve_status = $approve_status; // 审批状态
            $res->approve_status_name = $approve_status_name;// 审批状态名称


            $k = $res;
            // 采购订单状态 "新版：0 草稿 1 审批中 2 待签署采购合同 3 待支付定金 5 待配车 6 已完成 7 已作废 9 审批失败";

            $k->purchase_orders_status_name = IndexController::purchaseOrderStatusName($k->purchase_orders_status);


            $res = $k;
        }
        return json_encode($res);
    }
}